<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="list"
          size="big"
          border
          :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass"
        >
          <ElTableColumn label="员工姓名" width="150" prop="name" fixed="left"/>
          <ElTableColumn v-for="item in workDate" :label="item" width="120">
            <template slot-scope="{ row }" >
              <div
                class="hand"
                :class="{'hand-color1': row.schedules[item] == 0,
                        'hand-color2': row.schedules[item] == 1,
                        'hand-color3': row.schedules[item] == 2,
                        'hand-color4': row.schedules[item] == 3}"
                @click="clickGrids(row.id, row.shop_id, item, row.schedules[item])"
              >
                {{ row.schedules[item] == 0 ? '休' : 
                   row.schedules[item] == 1 ? '全天班' : 
                   row.schedules[item] == 2 ? '上午班' : '下午班' }}
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="一键排班" fixed="right" width="120">
            <template slot-scope="{ row }">
              <span class="theme" @click="setScheduleWeekSave(row.id)">一键排班</span>
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" fixed="right" width="120">
            <template slot-scope="{ row }">
              <span class="theme" @click="tapBtn('update', row.id)">编辑排班</span>
            </template>
          </ElTableColumn>
        </el-table>
      </el-col>
    </el-row>

   
    <el-dialog title="编辑排班" :visible.sync="dialogVisible" width="40%">
      <el-form :model="selectDate" label-width="150px">
        <el-form-item label="日期" >
          <el-input v-model="selectDate.date" placeholder="" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item label="排班类型" >
          <el-select v-model="selectDate.workType" placeholder="请选择排班类型" @change="onWorkTypeChange">
            <el-option
              v-for="item in selectDate.workTypeList"
              :key="item.workType"
              :label="item.text"
              :value="item.workType"
            >
            </el-option>
          </el-select>
        </el-form-item>
         <!-- 
    可预约时间      "kk_time": 0,   0没有设置   1已设置
    已预约时间      "yy_time": 0,   0没有预约   1已预约   2已被重复预约
    重复预约时间    "dd_time":0,    0没有设置   1已设置
    -->
        <!-- 可预约时间段选择 -->
        <el-form-item label="可预约时间段" v-if="selectDate.workType > 0">
          <div class="time_div">
            <div v-for="item in getAvailableTimeSlots" 
                 :key="`${item.start}-${item.end}`" 
                 :class="{
                   'time-disabled': item.yy_time !== 0,
                   'time-available': item.kk_time === 1 && item.yy_time === 0,
                 }"
                 @click="handleAppointmentClick(item)">
              {{item.start}}-{{ item.end }}
              <br>{{ item.yy_time !== 0 ? '已被预约' : '' }}
            </div>
          </div>
        </el-form-item>

        <!-- 可重复预约时间段选择 -->
        <el-form-item label="可重复预约时间段" v-if="selectDate.workType > 0">
          <div class="time_div">
            <div v-for="item in getAvailableTimeSlots" 
                 :key="`${item.start}-${item.end}`" 
                 :class="{
                   'time-disabled': item.yy_time === 2,
                   'time-repeat-available': item.dd_time === 1 && item.yy_time !== 2,
                 }"
                 @click="handleRepeatClick(item)">
                {{item.start}}-{{ item.end }}
               <br>{{ item.yy_time == 2 ? '已被重复预约' : '' }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { staffList, scheduleList, getShopBusinessTime, setSchedule, setScheduleWeek } from "@/api/staff";

export default {
  name: 'StaffSchedule',
  data() {
    return {
        
      options: {},
      workDate: [],
      list: [],
      amList: [],
      pmList: [],
      full_dayList: [],
      appointTime:[], // 点击可预约时间段
      repeatTime:[],// 点击可重复预约时间段
      dialogVisible: false,
      selectDate: {
        date: '',
        workType: '',
        id: '',
        shopId: '',
        workTypeList: [
          { workType: '0', text: "休" },
          { workType: '1', text: "全天班" },
          { workType: '2', text: "上午班" },
          { workType: '3', text: "下午班" }
        ]
      },
      colors: {
        primary: '#33bea7', // 主色调
        secondary: '#2bada8', // 辅助色
        disabled: '#909399', // 禁用色
        selected: '#33bea7' // 选中色
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    
    // 根据排班类型获取可用时间段
    getAvailableTimeSlots() {
      switch (this.selectDate.workType) {
        case '1': // 全天班
          return this.full_dayList;
        case '2': // 上午班
          return this.amList;
        case '3': // 下午班
          return this.pmList;
        default:
          return [];
      }
    },
    
  },
  watch: {},

  mounted() {
    this.getStaffList();
  },
  
  methods: {

    // 处理可预约时间段点击
    handleAppointmentClick(item) {
      // 如果时段不可预约，不执行任何操作
        if (item.yy_time !== 0) return;
        const timeKey = `${item.start}-${item.end}`;
        if(item.kk_time === 1){
            item.kk_time = 0;
              this.appointTime = this.appointTime.filter(
                time => `${time.start}-${time.end}` !== timeKey
                );
                console.log(this.appointTime,"this.appointTime")
        }else if(item.kk_time === 0){
            item.kk_time = 1;
            this.appointTime.push({'start':item.start,'end':item.end})
        }
    },
    
    // 处理可重复预约时间段点击
    handleRepeatClick(item) {
      // 如果时段不可重复预约，不执行任何操作
        if (item.yy_time === 2) return;
        const timeKey = `${item.start}-${item.end}`;
        if(item.dd_time === 1){
            item.dd_time = 0;
             this.repeatTime = this.repeatTime.filter(
                time => `${time.start}-${time.end}` !== timeKey
                );

        }else if(item.dd_time === 0){
            item.dd_time = 1;
            this.repeatTime.push({'start':item.start,'end':item.end})
        }
    },

    // 获取员工列表
    async getStaffList() {
      staffList({ shopId: this.userInfo.shop_id, page: 1, limit: 1000000 }).then((res) => {
        this.options.nurse_id = res.list;
        const staffIds = res.list.map(element => element.id);
        this.getStaffScheduleList(staffIds);
      });
    },

    // 获取当月员工排班列表
    async getStaffScheduleList(staffIds) {
      scheduleList({ staffIds: staffIds}).then((res) => {
        this.list = res.data.list;
        this.workDate = res.data.date_headers;
      })
    },
    // 点击单元格进行排班
    async clickGrids(id, shopId, date, workType) {
        
      
      await getShopBusinessTime({shop_id: shopId, shop_person_id: id, date: date}).then((res) => {
        this.amList = res.data.am;
        this.pmList = res.data.pm;
        this.full_dayList = res.data.full_day;
        this.onWorkTypeChange(workType);

      })


      this.dialogVisible = true;
      this.selectDate.date = date;
      this.selectDate.workType = workType.toString();

      this.selectDate.id = id;
      this.selectDate.shopId = shopId;
    },
    
    
    // 排班类型变更时
    onWorkTypeChange(e) {
        this.appointTime = [];
        this.repeatTime = [];
         if(e == 1){
            this.appointTime = this.full_dayList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => ({ start: item.start, end: item.end }));
            this.repeatTime = this.full_dayList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ({ start: item.start, end: item.end }));
          }else if(e == 2 ){
            this.appointTime = this.amList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => ({ start: item.start, end: item.end }));
            this.repeatTime = this.amList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ({ start: item.start, end: item.end }));
          }else if(e == 3){
            this.appointTime = this.pmList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => ({ start: item.start, end: item.end }));
            this.repeatTime = this.pmList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ({ start: item.start, end: item.end }));
          }
    
    },
    
    // 保存排班设置
    saveSchedule() {
        let params={
            // 准备提交的数据
            shop_id: this.userInfo.shop_id,
            shop_person_id: this.selectDate.id,
            is_work: this.selectDate.workType,
            time:this.selectDate.date,
            kk_time:{
                date:this.selectDate.date,
                time_slots:this.appointTime
            },
            dd_time:{
                date:this.selectDate.date,
                time_slots:this.repeatTime
            }
        }
        if(this.selectDate.workType == 0){
            params.kk_time = null;
            params.dd_time = null;
        }else if(this.selectDate.workType != 0 && params.dd_time.time_slots.length == 0){
            params.dd_time = null;
        }

      setSchedule(params).then((res) => {
        if (res.code !== 200) {
          this.$message({
            message: res.msg,
            type: 'warning'
          });
        } else {
          this.$message({
            message: res.msg || '排班设置成功',
            type: 'success'
          });
          this.dialogVisible = false;
          this.getStaffList();
        }
      });
    },
    
    // 一次排版一周
    setScheduleWeekSave(id) {
      setScheduleWeek({
        shop_id: this.userInfo.shop_id,
        shop_person_id: id
      }).then((res) => {
        if (res.code !== 200) {
          this.$message({
            message: res.msg,
            type: 'warning'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.getStaffList();
        }
      });
    },
    
    // 导航按钮
    tapBtn(type, id) {
      switch (type) {
        case "update":
          this.$router.push("./updateStaffSchedule?id=" + id + "&shop_id=" + this.userInfo.shop_id);
          break;
      }
    }
  }
};
</script>

<style lang="scss" scoped>

.time_div {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 8px 0;
  
  div {
    padding: 0 12px;
    border-radius: 4px;
    text-align: center;
    // min-width: 80px;
    transition: all 0.2s;
    cursor: pointer;
    border: 1px solid #EBEEF5;
  }
  
  .time-disabled {
    background-color: #909399;
    color: #fff;
    cursor: not-allowed;
  }
  
  .time-available {
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #33bea7;
    }
  }
  
  .time-selected {
    background-color: #33bea7;
    color: #fff;
    border-color: #33bea7;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .time-repeat-available {
    // background-color: #fff;
    // border: 1px solid #EBEEF5;
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #2bada8;
    }
  }
  
  .time-repeat-selected {
    background-color: #2bada8;
    color: #fff;
    border-color: #2bada8;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
}

.hand {
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  text-align: center;
}

.hand-color1 { background-color: ForestGreen; color: white; }
.hand-color2 { background-color: #dfe2e9; color: #6b849d; }
.hand-color3 { background-color: #2bada8; color: white; }
.hand-color4 { background-color: #c96bc2; color: white; }

.theme {
  color: #33bea7;
  cursor: pointer;
}
::v-deep .el-input{
    width: 220px !important;
}
</style>